package com.gaoyang.util;

import com.gaoyang.domain.DianPingUser;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ssports on 2016/12/22.
 */
public class FileUtil {

    public static void download(String urlString, String filename, String savePath, DianPingUser user) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        con.setRequestProperty("Accept","*/*");
        con.setRequestProperty("Accept-Encoding","gzip, deflate, br");
        con.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8");
        con.setRequestProperty("Connection","keep-alive");
        con.setRequestProperty("Cookie", "PHOENIX_ID=0a010879-15920812b3d-bf48d4; _hc.v=\"\\\"4a37d7ba-3da6-4987-a747-570c4b462e4f.1482309053\\\"\"; JSESSIONID=A58952430CACFB54534233A2475E748E; aburl=1; cy=1; cye=shanghai; ua=" + user.getUserName() + "; msource=default; default_ab=my%3AA%3A1; pvhistory=\"5oiR55qEPjo8L215Pjo8MTQ4MjMxNDI5MDEyN11fWw==\"; m_flash2=1");
        con.setRequestProperty("Host","www.dianping.com");
        con.setRequestProperty("Referer","https://mlogin.dianping.com/login/password?redir=https%3A%2F%2Fm.dianping.com%2Fmy");
        con.setRequestProperty("User-Agent","Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36");

        //设置请求超时为5s
        con.setConnectTimeout(5 * 1000);
        // 输入流
        InputStream is = con.getInputStream();

        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf = new File(savePath);
        if (!sf.exists()) {
            sf.mkdirs();
        }
        OutputStream os = new FileOutputStream(savePath + filename);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }

    public static List<String> readLastNLine(String filename, long numRead)
    {
        File file = new File(filename);
        // 定义结果集
        List<String> result = new ArrayList<String>();
        //行数统计
        long count = 0;

        // 排除不可读状态
        if (!file.exists() || file.isDirectory() || !file.canRead())
        {
            return null;
        }

        // 使用随机读取
        RandomAccessFile fileRead = null;
        try
        {
            //使用读模式
            fileRead = new RandomAccessFile(file, "r");
            //读取文件长度
            long length = fileRead.length();
            //如果是0，代表是空文件，直接返回空结果
            if (length == 0L)
            {
                return result;
            }
            else
            {
                //初始化游标
                long pos = length - 1;
                while (pos > 0)
                {
                    pos--;
                    //开始读取
                    fileRead.seek(pos);
                    //如果读取到\n代表是读取到一行
                    if (fileRead.readByte() == '\n')
                    {
                        //使用readLine获取当前行
                        String line = fileRead.readLine();
                        //保存结果
                        result.add(new String(line.getBytes("ISO-8859-1"),"utf-8"));

                        //行数统计，如果到达了numRead指定的行数，就跳出循环
                        count++;
                        if (count == numRead)
                        {
                            break;
                        }
                    }
                }
                if (pos == 0)
                {
                    fileRead.seek(0);
                    result.add(fileRead.readLine());
                }
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (fileRead != null)
            {
                try
                {
                    //关闭资源
                    fileRead.close();
                }
                catch (Exception e)
                {
                }
            }
        }

        return result;
    }

}
